#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <errno.h>

// 递归创建目录
int create_directory_recursive(const char* path) {
    char tmp[1024];
    char* p = NULL;
    size_t len;
    
    snprintf(tmp, sizeof(tmp), "%s", path);
    len = strlen(tmp);
    
    if (tmp[len - 1] == '/') {
        tmp[len - 1] = 0;
    }
    
    for (p = tmp + 1; *p; p++) {
        if (*p == '/') {
            *p = 0;
            if (mkdir(tmp, 0755) != 0 && errno != EEXIST) {
                return -1;
            }
            *p = '/';
        }
    }
    
    if (mkdir(tmp, 0755) != 0 && errno != EEXIST) {
        return -1;
    }
    
    return 0;
}

// 加载配置文件
int load_log_config(const char* config_file, log_config_t* config) {
    FILE* file = fopen(config_file, "r");
    if (!file) {
        // 使用默认配置
        strcpy(config->log_path, "./logs");
        config->max_file_size = 10 * 1024 * 1024; // 10MB
        strcpy(config->socket_path, "/tmp/log_server.sock");
        config->min_log_level = CLOG_INFO;
        config->buffer_size = 1024;  // 1KB 缓存
        config->flush_interval = 5;   // 5秒刷新间隔
        config->console_output = 1;   // 默认开启控制台输出
        return 0;
    }
    
    // 先设置默认值
    strcpy(config->log_path, "./logs");
    config->max_file_size = 10 * 1024 * 1024;
    strcpy(config->socket_path, "/tmp/log_server.sock");
    config->min_log_level = CLOG_INFO;
    config->buffer_size = 1024;
    config->flush_interval = 5;
    config->console_output = 1;
    
    char line[256];
    while (fgets(line, sizeof(line), file)) {
        // 去除换行符
        line[strcspn(line, "\n")] = 0;
        
        // 跳过注释和空行
        if (line[0] == '#' || line[0] == '\0') {
            continue;
        }
        
        char key[64], value[192];
        if (sscanf(line, "%63[^=]=%191s", key, value) == 2) {
            if (strcmp(key, "config_log_path") == 0) {
                strcpy(config->log_path, value);
            } else if (strcmp(key, "config_max_file_size") == 0) {
                config->max_file_size = atol(value);
            } else if (strcmp(key, "config_socket_path") == 0) {
                strcpy(config->socket_path, value);
            } else if (strcmp(key, "config_min_log_level") == 0) {
                config->min_log_level = parse_log_level(value);
                if (config->min_log_level == (clog_level_t)-1) {
                    config->min_log_level = CLOG_INFO; // 默认值
                }
            } else if (strcmp(key, "config_buffer_size") == 0) {
                config->buffer_size = atoi(value);
                if (config->buffer_size <= 0) {
                    config->buffer_size = 1024; // 默认值
                }
            } else if (strcmp(key, "config_flush_interval") == 0) {
                config->flush_interval = atoi(value);
                if (config->flush_interval <= 0) {
                    config->flush_interval = 5; // 默认值
                }
            } else if (strcmp(key, "config_console_output") == 0) {
                config->console_output = (strcmp(value, "true") == 0) ? 1 : 0;
            }
            // 兼容旧配置项（无前缀）
            else if (strcmp(key, "log_path") == 0) {
                strcpy(config->log_path, value);
            } else if (strcmp(key, "max_file_size") == 0) {
                config->max_file_size = atol(value);
            } else if (strcmp(key, "socket_path") == 0) {
                strcpy(config->socket_path, value);
            } else if (strcmp(key, "min_log_level") == 0) {
                config->min_log_level = parse_log_level(value);
                if (config->min_log_level == (clog_level_t)-1) {
                    config->min_log_level = CLOG_INFO;
                }
            } else if (strcmp(key, "buffer_size") == 0) {
                config->buffer_size = atoi(value);
                if (config->buffer_size <= 0) {
                    config->buffer_size = 1024;
                }
            } else if (strcmp(key, "flush_interval") == 0) {
                config->flush_interval = atoi(value);
                if (config->flush_interval <= 0) {
                    config->flush_interval = 5;
                }
            }
        }
    }
    
    fclose(file);
    return 0;
}

// 获取日志级别字符串
const char* get_level_string(clog_level_t level) {
    switch (level) {
        case CLOG_INFO: return "I";
        case CLOG_DEBUG: return "D";
        case CLOG_WARNING: return "W";
        case CLOG_ERROR: return "E";
        default: return "UNKNOWN";
    }
}

// 获取当前时间戳
void get_current_timestamp(char* buffer, size_t size) {
    time_t now = time(NULL);
    struct tm* tm_info = localtime(&now);
    strftime(buffer, size, "%Y-%m-%d %H:%M:%S", tm_info);
}

// 解析日志级别字符串
clog_level_t parse_log_level(const char* level_str) {
    if (strcmp(level_str, "info") == 0) return CLOG_INFO;
    if (strcmp(level_str, "debug") == 0) return CLOG_DEBUG;
    if (strcmp(level_str, "warning") == 0) return CLOG_WARNING;
    if (strcmp(level_str, "error") == 0) return CLOG_ERROR;
    return (clog_level_t)-1;
}
